<template>
  <view class="search-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text class="iconfont icon-back">←</text>
      </view>
      <view class="title">智能搜题</view>
      <view class="settings-btn" @click="toggleSettings">
        <text class="iconfont icon-settings">⚙️</text>
      </view>
      <view class="history-btn" @click="toggleHistory">
        <text class="iconfont icon-history">⏱</text>
      </view>
    </view>
    
    <!-- 搜索类型切换 -->
    <view class="search-type-tabs">
      <view 
        class="tab-item" 
        :class="{ active: searchType === 'text' }"
        @click="switchSearchType('text')"
      >
        <text>文本搜题</text>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: searchType === 'image' }"
        @click="switchSearchType('image')"
      >
        <text>拍照搜题</text>
      </view>
    </view>
    
    <!-- 文本搜索输入框 -->
    <view class="search-input-area" v-if="searchType === 'text'">
      <textarea 
        class="question-textarea" 
        v-model="textQuestion" 
        placeholder="请输入题目内容..." 
        :disabled="isSearching || resultsList.length > 0"
        auto-height
      />
      <view class="search-btn" @click="searchByText" :class="{ disabled: isSearching || !textQuestion.trim() }">
        <text>搜索</text>
      </view>
    </view>
    
    <!-- 图片搜索区域 -->
    <view class="image-search-area" v-if="searchType === 'image'">
      <view class="section-title">选择操作</view>
      
      <view class="image-action-buttons">
        <view class="action-button" @click="chooseImage">
          <image src="http://101.37.17.240:9000/zhxy/图片答疑.png" mode="aspectFit"></image>
          <text class="action-text">图像答疑</text>
        </view>
        <view class="action-button" @click="extractChineseText">
          <image src="http://101.37.17.240:9000/zhxy/图片抽取.png" mode="aspectFit"></image>
          <text class="action-text">图像抽取</text>
        </view>
        <view class="action-button" @click="processImageContent">
          <image src="http://101.37.17.240:9000/zhxy/图片问答.png" mode="aspectFit"></image>
          <text class="action-text">图像回答</text>
        </view>
        <view class="action-button">
          <image src="http://101.37.17.240:9000/zhxy/图像创作.png" mode="aspectFit"></image>
          <text class="action-text">图像创作</text>
        </view>
      </view>
      
      <view class="section-title">图片处理</view>
      
      <view class="image-upload-area">
        <view class="image-preview" v-if="imageUrl">
          <image :src="imageUrl" mode="aspectFit" class="preview-image"></image>
          <view class="remove-image" @click="removeImage">×</view>
        </view>
        <view class="upload-container" v-else @click="chooseImage">
          <view class="icon-button">
            <image src="http://101.37.17.240:9000/zhxy/上传图片.png" mode="aspectFit"></image>
            <text>上传图片</text>
          </view>
        </view>
      </view>

      <view class="image-processing-actions" v-if="imageUrl">
        <view class="process-button" @click="processImageContent">
          <text>总结图片内容 →</text>
        </view>
        <view class="process-button" @click="extractChineseText">
          <text>提取图中文字 →</text>
        </view>
      </view>
      
      <view class="section-title">提问</view>
      
      <view class="question-input-container">
        <textarea 
          class="question-textarea" 
          v-model="imageQuestion" 
          placeholder="请输入问题，例如描述一下图片内有什么" 
          :disabled="isSearching"
          auto-height
        />
        <view class="input-tools">
          <view class="expand-button">
            <image src="http://101.37.17.240:9000/zhxy/发送.png" mode="aspectFit"></image>
          </view>
          <view class="send-button" @click="searchByImage" :class="{ disabled: isSearching || (!imageUrl && !imageQuestion) }">
            <text class="send-icon">发送</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 搜索历史侧边栏 -->
    <view class="history-sidebar" :class="{ 'show-history': showHistory }">
      <view class="history-header">
        <text class="history-title">搜索历史</text>
        <view class="clear-history" @click="clearHistory">清空</view>
      </view>
      <view class="empty-history" v-if="searchHistory.length === 0">
        <text>暂无搜索历史</text>
      </view>
      <scroll-view class="history-list" scroll-y v-else>
        <view 
          class="history-item" 
          v-for="(item, index) in searchHistory" 
          :key="index" 
          @click="useHistoryItem(item)" 
          @longpress="showDeleteConfirm(index)"
        >
          <view class="history-content">
            <view class="history-type" :class="{ 'type-image': item.type === 'image' }">
              {{ item.type === 'text' ? '文本' : '图片' }}
            </view>
            <view class="history-text">{{ item.summary }}</view>
          </view>
          <view class="history-time">{{ formatTime(item.timestamp) }}</view>
        </view>
      </scroll-view>
      <view class="close-history" @click="toggleHistory">关闭</view>
    </view>
    
    <!-- 搜索结果列表 -->
    <view class="results-container" v-if="resultsList.length > 0">
      <view class="results-header">
        <text class="results-title">搜索结果</text>
        <view class="close-results" @click="clearResults">新搜索</view>
      </view>
      
      <scroll-view class="results-list" scroll-y>
        <view 
          class="result-item" 
          v-for="(item, index) in resultsList" 
          :key="index"
        >
          <view class="result-header">
            <view class="result-source">{{ item.source || '智能解析' }}</view>
            <view class="result-actions">
              <view class="action-btn copy-btn" @click="copyResult(item)">复制</view>
              <view class="action-btn share-btn" @click="shareResult(item)">分享</view>
            </view>
          </view>
          
          <view class="result-content" v-html="formatContent(item.content)"></view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 加载动画 -->
    <view class="loading-overlay" v-if="isSearching">
      <view class="loading-spinner"></view>
      <view class="loading-text">
        <view class="loading-title">正在处理中...</view>
        <view class="loading-details" v-if="searchType === 'image'">
          图片识别通常需要10-60秒，请耐心等待
        </view>
        <view class="loading-details" v-else>
          正在搜索相关答案，请稍候
        </view>
      </view>
    </view>
    
    <!-- 遮罩层 -->
    <view class="mask" v-if="showHistory" @click="toggleHistory"></view>

    <!-- API设置弹窗 -->
    <view class="settings-modal" v-if="showSettings">
      <view class="settings-popup">
        <view class="settings-header">
          <text class="settings-title">API设置</text>
        </view>
        <view class="settings-content">
          <view class="settings-item">
            <text class="settings-label">API地址</text>
            <input class="settings-input" v-model="apiBaseUrl" placeholder="请输入API基础地址" />
          </view>
          <view class="api-status">
            <text class="status-label">API状态:</text>
            <text :class="['status-value', apiStatus === 'online' ? 'status-online' : 
                                    apiStatus === 'offline' ? 'status-offline' : 'status-unknown']">
              {{ apiStatus === 'online' ? '在线' : 
                 apiStatus === 'offline' ? '离线' : '未知' }}
            </text>
            <button class="test-btn" @click="testApiConnection" :disabled="testingApi">测试连接</button>
          </view>
          <view class="settings-tips">
            <text>* 示例: http://localhost:8848/api/doubao</text>
            <text>* 此设置仅供开发调试使用</text>
          </view>
        </view>
        <view class="settings-footer">
          <view class="settings-btn cancel" @click="closeSettings">取消</view>
          <view class="settings-btn reset" @click="resetApiUrl">重置</view>
          <view class="settings-btn confirm" @click="saveApiUrl">保存</view>
        </view>
      </view>
      <view class="settings-mask" @click="closeSettings"></view>
    </view>

    <!-- 压缩图片用Canvas（隐藏） -->
    <canvas 
      canvas-id="compressCanvas" 
      :style="{width: canvasWidth + 'px', height: canvasHeight + 'px'}" 
      class="compress-canvas"
    ></canvas>
  </view>
</template>

<script>
import { 
  searchQuestionByText, 
  searchQuestionByImage, 
  getSearchHistory, 
  saveSearchHistory, 
  clearSearchHistory,
  setSearchApiBaseUrl,
  resetSearchApiBaseUrl
} from '../../api/searchAPI.js';

export default {
  data() {
    return {
      searchType: 'text', // 'text' 或 'image'
      textQuestion: '',
      imageQuestion: '', // 图片搜索的问题输入
      imageUrl: '',
      imageFile: null,
      isSearching: false,
      showHistory: false,
      resultsList: [],
      currentQuestion: '',
      searchHistory: getSearchHistory(),
      streamingResults: false,
      searchId: '',
      apiBaseUrl: '',
      showSettings: false,
      apiStatus: 'unknown',
      testingApi: false,
      canvasWidth: 0,
      canvasHeight: 0,
      selectedImageType: 'default',
      imageTypes: [
        { label: '通用题目', value: 'default' },
        { label: '数学公式', value: 'math' },
        { label: '文字题', value: 'text' },
        { label: '代码/算法', value: 'code' }
      ],
    }
  },
  onLoad() {
    // 加载历史记录
    this.loadSearchHistory();
    // 加载API设置
    this.loadApiSettings();
  },
  methods: {
    // 加载API设置
    loadApiSettings() {
      try {
        const apiBaseUrl = uni.getStorageSync('doubaoApiBaseUrl');
        this.apiBaseUrl = apiBaseUrl || '';
      } catch (e) {
        console.error('加载API设置失败:', e);
      }
    },

    // 切换搜索类型
    switchSearchType(type) {
      if (this.isSearching) return;
      this.searchType = type;
      this.clearResults();
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 清空结果，准备新搜索
    clearResults() {
      this.resultsList = [];
      this.currentQuestion = '';
      this.textQuestion = '';
      this.imageQuestion = '';
      this.imageUrl = '';
      this.imageFile = null;
    },
    
    // 选择图片
    async chooseImage() {
      try {
        // 设置loading状态
        uni.showLoading({
          title: '准备图片中...',
          mask: true
        });
        
        // 使用uni.chooseImage选择图片
        const result = await new Promise((resolve, reject) => {
          uni.chooseImage({
            count: 1, // 只选择一张图片
            sizeType: ['compressed'], // 默认压缩图片
            sourceType: ['album', 'camera'], // 从相册或拍照获取
            success: resolve,
            fail: reject
          });
        });
        
        // 获取选择的图片信息
        if (result && result.tempFiles && result.tempFiles.length > 0) {
          const file = result.tempFiles[0];
          const path = result.tempFilePaths[0];
          
          console.log('选择图片:', path, '大小:', file.size);
          
          // 图片信息提示
          uni.showLoading({
            title: '处理图片中...',
            mask: true
          });
          
          let finalFile = {
            path: path,
            size: file.size,
            type: file.type || 'image/jpeg'
          };
          
          // 如果图片太大，进行压缩
          if (file.size > 1024 * 1024) { // 大于1MB
            try {
              // #ifdef MP-WEIXIN
              // 微信平台使用微信压缩API
              const compressResult = await new Promise((resolve, reject) => {
                uni.compressImage({
                  src: path,
                  quality: file.size > 2 * 1024 * 1024 ? 60 : 75, // 根据大小调整压缩比例
                  success: resolve,
                  fail: reject
                });
              });
              
              // 获取压缩后文件信息
              const fileInfo = await new Promise((resolve, reject) => {
                uni.getFileInfo({
                  filePath: compressResult.tempFilePath,
                  success: resolve,
                  fail: reject
                });
              });
              
              finalFile = {
                path: compressResult.tempFilePath,
                size: fileInfo.size,
                type: 'image/jpeg'
              };
              
              console.log('图片已压缩, 新大小:', fileInfo.size);
              // #endif
              
              // #ifdef H5
              // H5环境使用Canvas压缩
              const compressedFile = await this.compressImageH5(file, 
                                     file.size > 3 * 1024 * 1024 ? 0.5 : // 大于3MB
                                     file.size > 2 * 1024 * 1024 ? 0.6 : // 大于2MB
                                     file.size > 1 * 1024 * 1024 ? 0.7 : 0.8 // 大于1MB或更小
                                   );
              
              finalFile = compressedFile;
              console.log('图片已压缩, 新大小:', compressedFile.size);
              // #endif
            } catch (error) {
              console.error('图片压缩失败，使用原图:', error);
            }
          }
          
          // 设置图片信息
          this.imageUrl = finalFile.path;
          this.imageFile = finalFile;
          
          // 如果已有搜索结果，清空
          if (this.resultsList.length > 0) {
            this.clearResults();
          }
          
          // 关闭loading
          uni.hideLoading();
          
          // 给用户压缩反馈
          if (file.size > finalFile.size) {
            const savingPercent = Math.round((1 - finalFile.size / file.size) * 100);
            if (savingPercent > 10) {
              uni.showToast({
                title: `已压缩${savingPercent}%`,
                icon: 'none',
                duration: 1500
              });
            }
          }
          
          return finalFile;
        }
      } catch (error) {
        console.error('选择图片失败:', error);
        
        uni.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
        
        return null;
      } finally {
        uni.hideLoading();
      }
    },
    
    // H5环境压缩图片方法 (更高效版)
    async compressImageH5(file, quality = 0.7) {
      return new Promise((resolve, reject) => {
        try {
          // 创建文件读取器
          const reader = new FileReader();
          
          reader.onload = (e) => {
            // 创建图片对象
            const img = new Image();
            
            img.onload = () => {
              // 获取图片尺寸
              let width = img.width;
              let height = img.height;
              
              // 计算压缩比例，限制最大尺寸为1600px
              const maxSize = 1600;
              if (width > maxSize || height > maxSize) {
                if (width > height) {
                  height = Math.round((height * maxSize) / width);
                  width = maxSize;
                } else {
                  width = Math.round((width * maxSize) / height);
                  height = maxSize;
                }
              }
              
              // 创建canvas
              const canvas = document.createElement('canvas');
              canvas.width = width;
              canvas.height = height;
              
              // 在canvas上绘制图片
              const ctx = canvas.getContext('2d');
              ctx.fillStyle = '#FFFFFF'; // 设置白色背景
              ctx.fillRect(0, 0, width, height);
              ctx.drawImage(img, 0, 0, width, height);
              
              // 将canvas转为Blob
              canvas.toBlob(
                (blob) => {
                  // 创建新的文件对象
                  resolve({
                    path: URL.createObjectURL(blob),
                    size: blob.size,
                    type: blob.type || 'image/jpeg',
                    blob: blob
                  });
                },
                'image/jpeg',
                quality
              );
            };
            
            img.onerror = reject;
            img.src = e.target.result;
          };
          
          reader.onerror = reject;
          reader.readAsDataURL(file);
        } catch (error) {
          reject(error);
        }
      });
    },
    
    // 移除图片
    removeImage() {
      this.imageUrl = '';
      this.imageFile = null;
    },
    
    // 文本搜索
    async searchByText() {
      if (this.isSearching || !this.textQuestion.trim()) return;
      
      this.currentQuestion = this.textQuestion.trim();
      this.isSearching = true;
      this.resultsList = [];
      this.streamingResults = true;
      
      try {
        // 检查网络状态
        const networkStatus = await this.checkNetworkStatus();
        if (!networkStatus) {
          throw new Error('网络连接不可用，请检查网络设置');
        }
        
        // 添加到历史记录
        this.addToHistory({
          type: 'text',
          summary: this.currentQuestion.length > 30 ? 
            this.currentQuestion.substring(0, 30) + '...' : 
            this.currentQuestion,
          content: this.currentQuestion,
          timestamp: new Date().getTime()
        });
        
        // 创建唯一搜索ID
        this.searchId = this.generateSearchId();
        
        // 初始结果占位符
        this.resultsList.push({
          content: '',
          source: '搜索中...',
          streaming: true
        });
        
        // 调用搜索API，增加超时处理
        const searchPromise = searchQuestionByText(
          this.currentQuestion,
          (content) => {
            // 流式更新结果
            if (this.resultsList.length > 0 && this.resultsList[0].streaming) {
              this.resultsList[0].content = content;
              this.resultsList[0].source = '智能解析';
            }
          }
        );
        
        // 添加超时处理
        const timeoutPromise = new Promise((_, reject) => {
          setTimeout(() => reject(new Error('搜索请求超时')), 90000); // 增加到90秒
        });
        
        // 等待搜索完成或超时
        await Promise.race([searchPromise, timeoutPromise]);
        
        // 搜索完成
        if (this.resultsList.length > 0) {
          this.resultsList[0].streaming = false;
        }
        
        // 分析结果，提取关键信息
        this.analyzeResult();
        
        // 延迟滚动到结果区域
        setTimeout(() => {
          const resultElement = document.querySelector('.results-container');
          if (resultElement) {
            resultElement.scrollIntoView({ behavior: 'smooth' });
          }
        }, 300);
        
      } catch (error) {
        console.error('搜索失败:', error);
        
        // 根据错误类型提供不同的错误提示
        let errorMessage = '搜索过程中出现错误，请重试。';
        
        if (error.message.includes('网络连接不可用')) {
          errorMessage = '网络连接不可用，请检查网络设置后重试。';
        } else if (error.message.includes('超时')) {
          errorMessage = '搜索请求超时，服务器可能暂时不可用，请稍后重试。';
        } else if (error.status >= 500) {
          errorMessage = '服务器暂时不可用，请稍后重试。';
        } else if (error.status === 404) {
          errorMessage = '搜索服务不可用，请确认API地址正确。';
        }
        
        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        });
        
        // 添加错误提示
        if (this.resultsList.length > 0 && this.resultsList[0].streaming) {
          this.resultsList[0].content = errorMessage;
          this.resultsList[0].source = '错误提示';
          this.resultsList[0].streaming = false;
        } else {
          this.resultsList.push({
            content: errorMessage,
            source: '错误提示',
            streaming: false
          });
        }
      } finally {
        this.isSearching = false;
        this.streamingResults = false;
      }
    },
    
    // 检查网络状态
    checkNetworkStatus() {
      return new Promise((resolve) => {
        uni.getNetworkType({
          success: (res) => {
            // 如果网络类型是none，则表示没有网络连接
            resolve(res.networkType !== 'none');
          },
          fail: () => {
            // 如果无法获取网络类型，假设有网络
            resolve(true);
          }
        });
      });
    },
    
    // 选择图片类型
    selectImageType(type) {
      this.selectedImageType = type;
    },
    
    // 图片搜索
    async searchByImage() {
      try {
        // 如果没有选择图片，先选择图片
        if (!this.imageUrl || !this.imageFile) {
          const imageResult = await this.chooseImage();
          
          // 如果选择图片后还是没有图片路径，中止搜索
          if (!this.imageUrl || !this.imageFile) {
            uni.showToast({
              title: '请先选择图片',
              icon: 'none'
            });
            return;
          }
          
          // 如果用户已经输入了问题，直接开始搜索
          if (this.imageQuestion.trim()) {
            // 延迟一下以确保UI更新
            setTimeout(() => {
              this.performImageSearch();
            }, 300);
            return;
          }
          
          // 如果没有输入问题，只是上传图片，不自动搜索
          return;
        }
        
        // 如果没有输入问题，提示用户
        if (!this.imageQuestion.trim()) {
          uni.showToast({
            title: '请输入您的问题',
            icon: 'none'
          });
          return;
        }
        
        // 如果已经有图片和问题，直接执行搜索
        this.performImageSearch();
      } catch (error) {
        console.error('图片搜索准备失败:', error);
        uni.showToast({
          title: '图片搜索准备失败',
          icon: 'none'
        });
      }
    },
    
    // 执行图片搜索操作
    async performImageSearch() {
      // 清空之前的结果
      this.resultsList = [];
      
      // 标记为搜索进行中
      this.isSearching = true;
      
      // 设置当前问题
      this.currentQuestion = this.imageQuestion.trim() || '图片题目';
      
      this.streamingResults = true;
      
      try {
        // 添加到历史记录
        this.addToHistory({
          type: 'image',
          summary: this.imageQuestion ? 
                  (this.imageQuestion.length > 20 ? this.imageQuestion.substring(0, 20) + '...' : this.imageQuestion) : 
                  ('图片搜题 - ' + this.getImageTypeLabel()),
          imageUrl: this.imageUrl,
          timestamp: new Date().getTime()
        });
        
        // 创建唯一搜索ID
        this.searchId = this.generateSearchId();
        
        // 初始结果占位符
        this.resultsList.push({
          content: '正在识别图片并分析内容，请稍候...\n\n图片处理可能需要10-60秒，请耐心等待。',
          source: '处理中',
          streaming: true
        });
        
        // 使用API进行搜索
        const result = await searchQuestionByImage(
          this.imageFile,
          (content) => {
            // 更新结果
            if (this.resultsList.length > 0 && this.resultsList[0].streaming) {
              // 检查是否是错误信息
              if (content.includes('图片识别失败') || content.includes('无法解析') || content.includes('无法识别')) {
                this.resultsList[0].content = content;
                this.resultsList[0].source = '识别失败';
                // 添加建议
                this.resultsList.push({
                  content: '您可以尝试以下方法：\n1. 使用更清晰的图片\n2. 调整拍摄角度，避免反光\n3. 直接使用文本搜题功能',
                  source: '建议',
                  streaming: false
                });
              } else {
                this.resultsList[0].content = content;
                this.resultsList[0].source = '识别结果';
              }
            }
          },
          null, // 不再需要systemPrompt参数
          'default', // 保留imageType以便前端分类
          null, // 不再需要model参数
          this.imageQuestion // 用户问题
        );
        
        // 搜索完成
        if (this.resultsList.length > 0) {
          this.resultsList[0].streaming = false;
        }
        
        // 分析结果，提取关键信息
        this.analyzeResult();
        
        // 延迟滚动到结果区域
        setTimeout(() => {
          const resultElement = document.querySelector('.results-container');
          if (resultElement) {
            resultElement.scrollIntoView({ behavior: 'smooth' });
          }
        }, 300);
      } catch (error) {
        console.error('图片搜索失败:', error);
        
        // 处理不同类型的错误
        let errorMessage = '图片识别过程中出现错误，请重试。';
        
        if (error.message) {
          if (error.message.includes('网络连接不可用')) {
            errorMessage = '网络连接不可用，请检查网络设置后重试。';
          } else if (error.message.includes('超时') || (error.error && error.error.errMsg && error.error.errMsg.includes('timeout'))) {
            errorMessage = '图片搜索请求超时，可能原因：\n1. 网络连接不稳定\n2. 图片过大\n3. 服务器处理时间过长\n\n请尝试：\n- 使用更小、更清晰的图片\n- 检查网络连接\n- 稍后再试';
          } else if (error.status >= 500) {
            errorMessage = '服务器暂时不可用，请稍后重试。';
          } else if (error.status === 404) {
            errorMessage = '图片识别服务不可用，请确认API地址正确。';
          } else if (error.message.includes('图片')) {
            errorMessage = '图片文件格式不支持或图片已损坏，请使用JPG、PNG格式的图片。';
          }
        }
        
        uni.showToast({
          title: '图片搜索失败',
          icon: 'none',
          duration: 3000
        });
        
        // 添加错误提示
        if (this.resultsList && this.resultsList.length > 0 && this.resultsList[0].streaming) {
          this.resultsList[0].content = errorMessage;
          this.resultsList[0].source = '错误提示';
          this.resultsList[0].streaming = false;
        } else {
          this.resultsList = [{
            content: errorMessage,
            source: '错误提示',
            streaming: false
          }];
        }
      } finally {
        this.isSearching = false;
        this.streamingResults = false;
      }
    },
    
    // 获取图片类型的显示文本
    getImageTypeLabel() {
      const type = this.imageTypes.find(t => t.value === this.selectedImageType);
      return type ? type.label : '通用题目';
    },
    
    // 分析结果，提取关键信息
    analyzeResult() {
      // 如果没有结果，直接返回
      if (this.resultsList.length === 0) return;
      
      const content = this.resultsList[0].content;
      
      // 尝试解析出题目和答案
      try {
        // 只保留分析部分和答案部分，移除重复的题目显示
        
        // 如果内容包含"题目："和"答案："，则拆分为不同结果项
        if (content.includes("题目：") && content.includes("答案：")) {
          // 直接获取答案部分，跳过题目部分（因为题目已经在上方显示）
          const answerPartIndex = content.indexOf("答案：");
          const answerPart = content.substring(answerPartIndex);
          
          // 检查是否还有解析部分
          let analysisPart = '';
          if (content.includes("解析：")) {
            const analysisIndex = content.indexOf("解析：");
            
            if (analysisIndex < answerPartIndex) {
              // 如果解析在答案之前
              analysisPart = content.substring(analysisIndex, answerPartIndex);
            } else {
              // 如果解析在答案之后
              analysisPart = content.substring(analysisIndex);
              // 更新答案部分，不包含解析
              const answerText = content.substring(answerPartIndex, analysisIndex);
              
              // 重设结果列表
              this.resultsList = [{
                content: answerText.trim(),
                source: '参考答案',
                streaming: false
              }, {
                content: analysisPart.trim(),
                source: '详细解析',
                streaming: false
              }];
              
              return; // 已处理完毕，直接返回
            }
          }
          
          // 更新结果列表，把答案放在第一位
          this.resultsList = [{
            content: this.formatAnswerForDisplay(answerPart.trim()),
            source: '参考答案',
            streaming: false
          }];
          
          // 如果有解析部分，添加到结果列表
          if (analysisPart) {
            this.resultsList.push({
              content: analysisPart.trim(),
              source: '详细解析',
              streaming: false
            });
          }
        }
        // 如果内容包含"解析"和"答案"，但格式不完全匹配上面的格式
        else if (content.includes("解析") && content.includes("答案")) {
          // 尝试从内容中提取答案部分
          let answerMatch = content.match(/答案[:：][\s\S]+?(?=\n\n|解析[:：]|$)/);
          let analysisMatch = content.match(/解析[:：][\s\S]+?(?=$)/);
          
          if (answerMatch) {
            const answerContent = answerMatch[0].trim();
            
            // 创建新的结果列表，先放答案
            let newResults = [{
              content: this.formatAnswerForDisplay(answerContent),
              source: '答案',
              streaming: false
            }];
            
            // 如果有解析，添加解析
            if (analysisMatch) {
              newResults.push({
                content: analysisMatch[0].trim(),
                source: '解析',
                streaming: false
              });
            } else {
              // 尝试提取非答案部分作为解析
              const fullContent = content.trim();
              const otherContent = fullContent.replace(answerMatch[0], '').trim();
              
              if (otherContent && !otherContent.includes("题目：")) {
                newResults.push({
                  content: otherContent,
                  source: '题目分析',
                  streaming: false
                });
              }
            }
            
            this.resultsList = newResults;
          }
        } 
        // 如果没有明确的"答案："标记，但内容较长，尝试提取最后部分作为答案
        else if (content.length > 100 && !this.streamingResults) {
          // 检查是否有明显的结论标记
          const conclusionMarkers = ['因此', '所以', '综上', '结论', '答案', '故'];
          let conclusionIndex = -1;
          
          // 寻找最后出现的结论标记
          for (const marker of conclusionMarkers) {
            const idx = content.lastIndexOf(marker);
            if (idx > conclusionIndex && idx > content.length * 0.6) { // 至少在内容的60%之后
              conclusionIndex = idx;
            }
          }
          
          if (conclusionIndex > 0) {
            // 将内容分为分析和答案两部分
            const analysisPart = content.substring(0, conclusionIndex).trim();
            const answerPart = content.substring(conclusionIndex).trim();
            
            // 更新结果列表 - 把答案放在前面
            this.resultsList = [{
              content: this.formatAnswerForDisplay(answerPart),
              source: '答案',
              streaming: false
            }];
            
            // 如果分析部分不为空，添加到结果中
            if (analysisPart) {
              this.resultsList.push({
                content: analysisPart,
                source: '分析过程',
                streaming: false
              });
            }
          }
        }
      } catch (error) {
        console.warn('结果分析失败:', error);
        // 分析失败时，保持原有结果但强调显示
        if (this.resultsList.length > 0) {
          this.resultsList[0].content = this.formatAnswerForDisplay(this.resultsList[0].content);
        }
      }
    },
    
    // 格式化答案以增强显示效果
    formatAnswerForDisplay(answerText) {
      if (!answerText) return '';
      
      // 已包含"答案："前缀的情况
      if (answerText.includes('答案：')) {
        // 强调答案部分
        return answerText.replace(
          /答案[:：]\s*([\s\S]*?)(?=(\n\n解析[:：])|$)/s,
          (match, p1) => `答案：<strong>${p1.trim()}</strong>`
        );
      }
      
      // 没有前缀的情况，整体作为答案强调
      return `<strong>${answerText}</strong>`;
    },
    
    // 复制结果
    copyResult(item) {
      const plainText = this.stripHtml(item.content);
      uni.setClipboardData({
        data: plainText,
        success: () => {
          uni.showToast({
            title: '已复制到剪贴板',
            icon: 'success'
          });
        }
      });
    },
    
    // 分享结果
    shareResult(item) {
      uni.showToast({
        title: '分享功能开发中',
        icon: 'none'
      });
    },
    
    // 格式化内容，增强显示效果
    formatContent(content) {
      if (!content) return '';
      
      let formatted = content;
      
      // 将markdown风格的加粗转为HTML
      formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
      
      // 突出显示关键答案标记
      formatted = formatted.replace(/(答案[:：])/g, '<span style="color:#8A2BE2;font-weight:bold">$1</span>');
      formatted = formatted.replace(/(解析[:：])/g, '<span style="color:#1890ff;font-weight:bold">$1</span>');
      
      // 处理换行
      formatted = formatted.replace(/\n/g, '<br>');
      
      // 处理数学公式相关符号
      formatted = formatted.replace(/([=×÷\+\-])/g, '<span style="padding:0 3px">$1</span>');
      
      // 突出显示数值部分
      formatted = formatted.replace(/(\d+\.?\d*)/g, '<span style="color:#ff4d4f;font-weight:500">$1</span>');
      
      return formatted;
    },
    
    // 去除HTML标签
    stripHtml(html) {
      if (!html) return '';
      return html.replace(/<[^>]*>/g, '').replace(/<br>/g, '\n');
    },
    
    // 预览图片
    previewImage(url) {
      uni.previewImage({
        current: url,
        urls: [url]
      });
    },
    
    // 切换历史记录显示
    toggleHistory() {
      this.showHistory = !this.showHistory;
    },
    
    // 加载搜索历史
    loadSearchHistory() {
      this.searchHistory = getSearchHistory();
    },
    
    // 添加到历史记录
    addToHistory(item) {
      // 添加到历史记录开头
      this.searchHistory.unshift(item);
      
      // 限制历史记录数量为20条
      if (this.searchHistory.length > 20) {
        this.searchHistory = this.searchHistory.slice(0, 20);
      }
      
      // 保存到本地存储
      this.saveSearchHistory();
    },
    
    // 保存搜索历史
    saveSearchHistory() {
      saveSearchHistory(this.searchHistory);
    },
    
    // 清空历史记录
    clearHistory() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有搜索历史吗？',
        success: (res) => {
          if (res.confirm) {
            this.searchHistory = [];
            clearSearchHistory();
          }
        }
      });
    },
    
    // 删除单条历史记录
    showDeleteConfirm(index) {
      uni.showModal({
        title: '删除记录',
        content: '确定要删除这条搜索记录吗？',
        success: (res) => {
          if (res.confirm) {
            this.searchHistory.splice(index, 1);
            this.saveSearchHistory();
          }
        }
      });
    },
    
    // 使用历史记录项
    useHistoryItem(item) {
      if (this.isSearching) return;
      
      this.toggleHistory();
      this.clearResults();
      
      if (item.type === 'text') {
        this.searchType = 'text';
        this.textQuestion = item.content;
        setTimeout(() => {
          this.searchByText();
        }, 300);
      } else {
        this.searchType = 'image';
        // 注意：历史记录中的图片URL可能已失效，实际应用中可能需要重新上传
        if (item.imageUrl) {
          this.imageUrl = item.imageUrl;
          setTimeout(() => {
            this.searchByImage();
          }, 300);
        }
      }
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp);
      const today = new Date();
      
      // 如果是今天
      if (date.toDateString() === today.toDateString()) {
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        return `今天 ${hours}:${minutes}`;
      }
      
      // 如果是昨天
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      if (date.toDateString() === yesterday.toDateString()) {
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        return `昨天 ${hours}:${minutes}`;
      }
      
      // 其他日期
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${month}-${day}`;
    },

    // API设置弹窗
    toggleSettings() {
      this.showSettings = true;
    },

    closeSettings() {
      this.showSettings = false;
    },

    resetApiUrl() {
      this.apiBaseUrl = '';
      resetSearchApiBaseUrl();
      uni.showToast({
        title: '已恢复默认API地址',
        icon: 'none'
      });
    },

    saveApiUrl() {
      if (this.apiBaseUrl.trim()) {
        // 验证URL格式
        if (!this.apiBaseUrl.startsWith('http://') && !this.apiBaseUrl.startsWith('https://')) {
          uni.showToast({
            title: 'URL格式不正确，请以http://或https://开头',
            icon: 'none',
            duration: 3000
          });
          return;
        }
        
        // 保存API设置
        const success = setSearchApiBaseUrl(this.apiBaseUrl.trim());
        if (success) {
          uni.showToast({
            title: 'API地址已保存',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: '保存失败，请重试',
            icon: 'none'
          });
        }
      } else {
        // 如果输入为空，恢复默认设置
        resetSearchApiBaseUrl();
        uni.showToast({
          title: '已恢复默认API地址',
          icon: 'none'
        });
      }
      this.closeSettings();
    },

    async testApiConnection() {
      this.testingApi = true;
      this.apiStatus = 'unknown';
      
      try {
        // 检查网络状态
        const networkStatus = await this.checkNetworkStatus();
        if (!networkStatus) {
          throw new Error('网络连接不可用，请检查网络设置');
        }
        
        // 测试API地址有效性
        if (!this.apiBaseUrl || !this.apiBaseUrl.startsWith('http')) {
          this.apiStatus = 'offline';
          uni.showToast({
            title: 'API地址格式无效',
            icon: 'none'
          });
          return;
        }
        
        // 构建测试URL
        const testUrl = this.apiBaseUrl.endsWith('/') ? 
          this.apiBaseUrl + 'chat' : 
          this.apiBaseUrl + '/chat';
        
        // 使用uni.request测试API连接
        await new Promise((resolve, reject) => {
          uni.request({
            url: testUrl,
            method: 'POST',
            timeout: 5000, // 5秒超时
            data: {
              question: "测试API连接",
              systemPrompt: "简单回复'测试成功'即可"
            },
            header: {
              'Content-Type': 'application/json'
            },
            success: (res) => {
              if (res.statusCode >= 200 && res.statusCode < 300) {
                this.apiStatus = 'online';
                resolve(res);
              } else {
                reject(new Error(`HTTP错误: ${res.statusCode}`));
              }
            },
            fail: (err) => {
              reject(err);
            }
          });
        });
        
        uni.showToast({
          title: 'API连接测试成功',
          icon: 'success'
        });
      } catch (error) {
        console.error('API连接测试失败:', error);
        this.apiStatus = 'offline';
        uni.showToast({
          title: 'API连接测试失败',
          icon: 'none'
        });
      } finally {
        this.testingApi = false;
      }
    },

    // 生成唯一搜索ID
    generateSearchId() {
      return Date.now().toString(36) + Math.random().toString(36).substr(2);
    },

    // 处理图片内容，生成概述
    processImageContent() {
      if (!this.imageUrl || !this.imageFile) {
        uni.showToast({
          title: '请先上传图片',
          icon: 'none'
        });
        return;
      }

      // 设置问题提示，使模型总结图片内容
      this.imageQuestion = "请详细描述一下这张图片中的内容";
      
      // 自动开始搜索
      this.performImageSearch();
    },
    
    // 提取图片中的文字
    extractChineseText() {
      if (!this.imageUrl || !this.imageFile) {
        uni.showToast({
          title: '请先上传图片',
          icon: 'none'
        });
        return;
      }

      // 设置问题提示，使模型提取图片中的文字
      this.imageQuestion = "请提取并返回图片中的所有中文文字内容，保持原始格式";
      
      // 自动开始搜索
      this.performImageSearch();
    },
  }
}
</script>

<style lang="scss">
.search-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f7fa;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background: linear-gradient(135deg, #8A2BE2, #9370DB);
  position: relative;
  z-index: 10;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
  
  .back-btn, .history-btn, .settings-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .iconfont {
      font-size: 40rpx;
      color: #fff;
    }
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 36rpx;
    font-weight: bold;
    color: #fff;
    text-shadow: 0 1px 2px rgba(0,0,0,0.1);
  }
}

.search-type-tabs {
  display: flex;
  background: #fff;
  padding: 20rpx 0;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
  
  .tab-item {
    flex: 1;
    text-align: center;
    font-size: 30rpx;
    color: #666;
    position: relative;
    padding: 10rpx 0;
    
    &.active {
      color: #8A2BE2;
      font-weight: bold;
      
      &::after {
        content: '';
        position: absolute;
        bottom: -10rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 6rpx;
        background-color: #8A2BE2;
        border-radius: 3rpx;
      }
    }
  }
}

.search-input-area {
  margin: 30rpx;
  
  .question-textarea {
    width: 100%;
    min-height: 200rpx;
    background: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    font-size: 30rpx;
    box-sizing: border-box;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08);
    border: 1px solid rgba(138, 43, 226, 0.1);
  }
}

.search-btn {
  width: 100%;
  height: 90rpx;
  background: linear-gradient(135deg, #8A2BE2, #9370DB);
  border-radius: 45rpx;
  color: #fff;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  box-shadow: 0 4rpx 12rpx rgba(138, 43, 226, 0.2);
  
  &:active {
    transform: scale(0.98);
    opacity: 0.9;
  }
  
  &.disabled {
    background: #cccccc;
    opacity: 0.8;
    box-shadow: none;
  }
}

.image-search-area {
  margin: 30rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin: 30rpx 0 15rpx;
    position: relative;
    padding-left: 15rpx;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 6rpx;
      height: 24rpx;
      background-color: #8A2BE2;
      border-radius: 3rpx;
    }
    
    &:first-child {
      margin-top: 0;
    }
  }
  
  .image-action-buttons {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30rpx;
    
    .action-button {
      flex: 1;
      text-align: center;
      padding: 20rpx 0;
      background: #fff;
      border-radius: 12rpx;
      margin-right: 15rpx;
      box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.08);
      transition: all 0.3s ease;
      
      &:last-child {
        margin-right: 0;
      }
      
      &:active {
        transform: scale(0.96);
        background: rgba(138, 43, 226, 0.1);
      }
      
      image {
        width: 60rpx;
        height: 60rpx;
        margin: 0 auto 12rpx;
        display: block;
      }
      
      .action-text {
        font-size: 24rpx;
        color: #333;
        font-weight: 500;
      }
    }
  }
  
  .image-upload-area {
    margin-bottom: 20rpx;
    
    .image-preview {
      width: 100%;
      height: 420rpx;
      background: #fff;
      border-radius: 16rpx;
      position: relative;
      overflow: hidden;
      margin-bottom: 20rpx;
      box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08);
      border: 1px solid rgba(138, 43, 226, 0.1);
      display: flex;
      align-items: center;
      justify-content: center;
      
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 8rpx;
        background: linear-gradient(to right, #8A2BE2, #9370DB);
        opacity: 0.5;
      }
      
      .preview-image {
        max-width: 100%;
        max-height: 400rpx;
        object-fit: contain;
      }
      
      .remove-image {
        position: absolute;
        top: 20rpx;
        right: 20rpx;
        width: 60rpx;
        height: 60rpx;
        background: rgba(0,0,0,0.5);
        color: #fff;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 40rpx;
        z-index: 2;
        box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.2);
        
        &:active {
          transform: scale(0.95);
          background: rgba(0,0,0,0.7);
        }
      }
    }
    
    .upload-container {
      width: 100%;
      height: 320rpx;
      background: #f9f9f9;
      border-radius: 16rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin-bottom: 20rpx;
      box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
      border: 2rpx dashed rgba(138, 43, 226, 0.3);
      position: relative;
      overflow: hidden;
      
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 8rpx;
        background: linear-gradient(to right, #8A2BE2, #9370DB);
        opacity: 0.5;
      }
      
      .icon-button {
        display: flex;
        flex-direction: column;
        align-items: center;
        
        image {
          width: 110rpx;
          height: 110rpx;
          margin-bottom: 24rpx;
        }
        
        text {
          font-size: 30rpx;
          color: #666;
          background: rgba(138, 43, 226, 0.08);
          padding: 8rpx 30rpx;
          border-radius: 30rpx;
        }
      }
    }
  }

  .image-processing-actions {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30rpx;
    
    .process-button {
      flex: 1;
      text-align: center;
      padding: 20rpx 0;
      background: #f8f8f8;
      border-radius: 12rpx;
      margin-right: 15rpx;
      box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
      transition: all 0.3s;
      border: 1px solid rgba(138, 43, 226, 0.1);
      
      &:last-child {
        margin-right: 0;
      }
      
      &:active {
        transform: scale(0.96);
        background: rgba(138, 43, 226, 0.1);
      }
      
      text {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }
    }
  }
  
  .question-input-container {
    margin-bottom: 30rpx;
    
    .question-textarea {
      width: 100%;
      min-height: 120rpx;
      background: #fff;
      border-radius: 16rpx 16rpx 0 0;
      padding: 24rpx;
      font-size: 30rpx;
      box-sizing: border-box;
      margin-bottom: 0;
      box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08);
      border: 1px solid rgba(138, 43, 226, 0.1);
    }
    
    .input-tools {
      display: flex;
      background: #fff;
      border-radius: 0 0 16rpx 16rpx;
      padding: 15rpx 20rpx 20rpx;
      border-top: 1rpx solid #f5f5f5;
      box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08);
      
      .expand-button {
        width: 70rpx;
        height: 70rpx;
        border-radius: 50%;
        background: #f8f8f8;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15rpx;
        transition: all 0.3s ease;
        
        &:active {
          transform: scale(0.9);
          background: rgba(138, 43, 226, 0.1);
        }
        
        .expand-icon {
          font-size: 36rpx;
          color: #666;
        }
      }
      
      .send-button {
        flex: 1;
        height: 70rpx;
        background: linear-gradient(135deg, #8A2BE2, #9370DB);
        border-radius: 35rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
        box-shadow: 0 4rpx 12rpx rgba(138, 43, 226, 0.2);
        
        &:active {
          transform: scale(0.97);
          opacity: 0.9;
        }
        
        &.disabled {
          background: #cccccc;
          opacity: 0.7;
          box-shadow: none;
        }
        
        .send-icon {
          font-size: 36rpx;
          color: #fff;
        }
      }
    }
  }
}

.history-sidebar {
  position: fixed;
  top: 0;
  right: -600rpx;
  width: 600rpx;
  height: 100vh;
  background: #fff;
  z-index: 100;
  box-shadow: -2rpx 0 10rpx rgba(0,0,0,0.1);
  transition: right 0.3s ease;
  display: flex;
  flex-direction: column;
  
  &.show-history {
    right: 0;
  }
  
  .history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .history-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .clear-history {
      font-size: 26rpx;
      color: #999;
    }
  }
  
  .empty-history {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #999;
    font-size: 28rpx;
  }
  
  .history-list {
    flex: 1;
    
    .history-item {
      padding: 20rpx 30rpx;
      border-bottom: 1rpx solid #f0f0f0;
      
      .history-content {
        display: flex;
        align-items: flex-start;
        margin-bottom: 10rpx;
        
        .history-type {
          background: #e6f7ff;
          color: #1890ff;
          font-size: 22rpx;
          padding: 4rpx 12rpx;
          border-radius: 4rpx;
          margin-right: 10rpx;
          flex-shrink: 0;
          
          &.type-image {
            background: #f6ffed;
            color: #52c41a;
          }
        }
        
        .history-text {
          font-size: 28rpx;
          color: #333;
          flex: 1;
        }
      }
      
      .history-time {
        font-size: 24rpx;
        color: #999;
        text-align: right;
      }
    }
  }
  
  .close-history {
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f5f5;
    color: #666;
    font-size: 28rpx;
  }
}

.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  z-index: 90;
}

.results-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  margin: 30rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.08);
  max-height: calc(100vh - 380rpx); /* Maximize available height */
  
  .results-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    background-color: #fcfcfc;
    
    .results-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .close-results {
      font-size: 28rpx;
      color: #8A2BE2;
      font-weight: 500;
      background-color: rgba(138, 43, 226, 0.1);
      padding: 6rpx 15rpx;
      border-radius: 30rpx;
    }
  }
  
  .results-list {
    flex: 1;
    overflow-y: auto;
    padding-bottom: 30rpx; /* Extra padding for better scrolling */
    
    .result-item {
      padding: 30rpx;
      
      &:not(:last-child) {
        border-bottom: 1rpx solid #f0f0f0;
      }
      
      .result-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
        
        .result-source {
          font-size: 26rpx;
          color: #8A2BE2;
          background: rgba(138,43,226,0.1);
          padding: 8rpx 16rpx;
          border-radius: 6rpx;
          font-weight: 500;
        }
        
        .result-actions {
          display: flex;
          
          .action-btn {
            font-size: 26rpx;
            padding: 6rpx 14rpx;
            margin-left: 15rpx;
            border-radius: 4rpx;
            transition: all 0.3s;
            
            &:active {
              opacity: 0.7;
            }
          }
          
          .copy-btn {
            color: #1890ff;
            background-color: rgba(24, 144, 255, 0.1);
            border-radius: 30rpx;
          }
          
          .share-btn {
            color: #52c41a;
            background-color: rgba(82, 196, 26, 0.1);
            border-radius: 30rpx;
          }
        }
      }
      
      .result-content {
        font-size: 32rpx;
        color: #333;
        line-height: 1.8;
        background-color: #fff;
        padding: 10rpx;
        word-break: break-all; /* Ensure content wraps properly */
        
        strong {
          color: #000;
          font-weight: bold;
        }
      }
      
      // 特别强调答案样式 - 第一个结果简洁显示，着重突出后面的答案
      &:first-child {
        padding-bottom: 15rpx;
        
        .result-content {
          max-height: 300rpx;
          overflow-y: auto;
        }
      }
      
      // 答案显示样式增强
      &:not(:first-child) {
        background-color: #f9feff;
        margin: 0 15rpx 15rpx;
        border-radius: 12rpx;
        box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
        
        .result-content {
          padding: 20rpx;
          border-radius: 12rpx;
          border-left: 8rpx solid #8A2BE2;
          box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
        }
      }
    }
  }
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255,255,255,0.96);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 999;
  backdrop-filter: blur(5px);
  
  .loading-spinner {
    width: 90rpx;
    height: 90rpx;
    border-radius: 50%;
    border: 6rpx solid #f3f3f3;
    border-top: 6rpx solid #8A2BE2;
    animation: spin 1s linear infinite;
    margin-bottom: 40rpx;
    box-shadow: 0 4rpx 10rpx rgba(0,0,0,0.05);
  }
  
  .loading-text {
    text-align: center;
    padding: 0 40rpx;
    
    .loading-title {
      font-size: 34rpx;
      color: #333;
      margin-bottom: 16rpx;
      font-weight: 600;
    }
    
    .loading-details {
      font-size: 28rpx;
      color: #666;
      max-width: 80%;
      margin: 0 auto;
      line-height: 1.5;
    }
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
}

.settings-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .settings-popup {
    width: 650rpx;
    background: #fff;
    border-radius: 16rpx;
    overflow: hidden;
    z-index: 101;
    
    .settings-header {
      padding: 30rpx;
      text-align: center;
      border-bottom: 1rpx solid #f0f0f0;
      
      .settings-title {
        font-size: 34rpx;
        font-weight: bold;
        color: #333;
      }
    }
    
    .settings-content {
      padding: 30rpx;
      
      .settings-item {
        margin-bottom: 20rpx;
        
        .settings-label {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 10rpx;
          display: block;
        }
        
        .settings-input {
          width: 100%;
          height: 80rpx;
          background: #f5f7fa;
          border-radius: 8rpx;
          padding: 0 20rpx;
          font-size: 28rpx;
          color: #333;
        }
      }
      
      .api-status {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;
        
        .status-label {
          font-size: 28rpx;
          color: #333;
          margin-right: 10rpx;
        }
        
        .status-value {
          font-size: 28rpx;
          color: #333;
          padding: 4rpx 12rpx;
          border-radius: 4rpx;
          margin-right: 10rpx;
          
          &.status-online {
            background: #f6ffed;
            color: #52c41a;
          }
          
          &.status-offline {
            background: #fff1f0;
            color: #ff4d4f;
          }
          
          &.status-unknown {
            background: #f5f5f5;
            color: #999;
          }
        }
        
        .test-btn {
          font-size: 28rpx;
          color: #8A2BE2;
          padding: 4rpx 12rpx;
          border-radius: 4rpx;
          border: 1rpx solid #8A2BE2;
          background: none;
          margin-left: 10rpx;
          
          &:disabled {
            color: #cccccc;
            border-color: #cccccc;
          }
        }
      }
      
      .settings-tips {
        font-size: 24rpx;
        color: #999;
        
        text {
          display: block;
          line-height: 1.5;
        }
      }
    }
    
    .settings-footer {
      display: flex;
      border-top: 1rpx solid #f0f0f0;
      
      .settings-btn {
        flex: 1;
        height: 100rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 30rpx;
        
        &.cancel {
          color: #999;
          border-right: 1rpx solid #f0f0f0;
        }
        
        &.reset {
          color: #ff9800;
          border-right: 1rpx solid #f0f0f0;
        }
        
        &.confirm {
          color: #8A2BE2;
          font-weight: bold;
        }
      }
    }
  }
  
  .settings-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.5);
    z-index: 100;
  }
}

.compress-canvas {
  position: fixed;
  left: -9999px;
  top: -9999px;
  z-index: -1;
  opacity: 0;
}
</style> 